<template>
  <el-form-item 
    :label="field.label" 
    :prop="field.key"
    :class="fieldClass"
    v-show="isVisible"
  >
    <!-- 字符串输入 -->
    <el-input
      v-if="field.type === 'string'"
      :model-value="value"
      @update:model-value="updateValue"
      :placeholder="field.placeholder"
      :disabled="isDisabled"
      clearable
    />

    <!-- 多行文本 -->
    <el-input
      v-else-if="field.type === 'textarea'"
      :model-value="value"
      @update:model-value="updateValue"
      type="textarea"
      :placeholder="field.placeholder"
      :disabled="isDisabled"
      :rows="3"
    />

    <!-- 数字输入 -->
    <el-input-number
      v-else-if="field.type === 'number'"
      :model-value="value"
      @update:model-value="updateValue"
      :min="field.min"
      :max="field.max"
      :step="field.step || 1"
      :disabled="isDisabled"
      controls-position="right"
      style="width: 200px"
    />

    <!-- 范围输入 -->
    <div v-else-if="field.type === 'range'" class="range-input">
      <el-input-number
        :model-value="value?.min || 0"
        @update:model-value="(val) => updateRangeValue('min', val)"
        :min="field.min"
        :max="value?.max || field.max"
        :disabled="isDisabled"
        placeholder="最小值"
        style="width: 120px"
      />
      <span class="range-separator">-</span>
      <el-input-number
        :model-value="value?.max || 0"
        @update:model-value="(val) => updateRangeValue('max', val)"
        :min="value?.min || field.min"
        :max="field.max"
        :disabled="isDisabled"
        placeholder="最大值"
        style="width: 120px"
      />
    </div>

    <!-- 布尔值开关 -->
    <el-switch
      v-else-if="field.type === 'boolean'"
      :model-value="value"
      @update:model-value="updateValue"
      :disabled="isDisabled"
    />

    <!-- 单选下拉 -->
    <el-select
      v-else-if="field.type === 'select'"
      :model-value="value"
      @update:model-value="updateValue"
      :placeholder="field.placeholder || `请选择${field.label}`"
      :disabled="isDisabled"
      clearable
      style="width: 100%"
    >
      <el-option
        v-for="option in fieldOptions"
        :key="option.value"
        :label="option.label"
        :value="option.value"
        :disabled="option.disabled"
      >
        <div class="option-content">
          <el-icon v-if="option.icon" style="margin-right: 8px">
            <component :is="option.icon" />
          </el-icon>
          <span>{{ option.label }}</span>
          <span v-if="option.description" class="option-description">
            {{ option.description }}
          </span>
        </div>
      </el-option>
    </el-select>

    <!-- 多选下拉 -->
    <el-select
      v-else-if="field.type === 'multiSelect'"
      :model-value="value || []"
      @update:model-value="updateValue"
      multiple
      :placeholder="field.placeholder || `请选择${field.label}`"
      :disabled="isDisabled"
      style="width: 100%"
    >
      <el-option
        v-for="option in fieldOptions"
        :key="option.value"
        :label="option.label"
        :value="option.value"
        :disabled="option.disabled"
      />
    </el-select>

    <!-- 标签输入 -->
    <div v-else-if="field.type === 'tags'" class="tags-input">
      <el-tag
        v-for="tag in (value || [])"
        :key="tag"
        closable
        @close="removeTag(tag)"
        style="margin-right: 8px; margin-bottom: 8px;"
      >
        {{ tag }}
      </el-tag>
      <el-input
        v-if="tagInputVisible"
        ref="tagInput"
        v-model="tagInputValue"
        size="small"
        style="width: 120px"
        @keyup.enter="handleTagInputConfirm"
        @blur="handleTagInputConfirm"
      />
      <el-button
        v-else
        size="small"
        @click="showTagInput"
        :disabled="isDisabled"
      >
        <el-icon><Plus /></el-icon>
        添加{{ field.label }}
      </el-button>
    </div>

    <!-- 表情符号选择器 -->
    <div v-else-if="field.type === 'emoji'" class="emoji-input">
      <el-input
        :model-value="value"
        @update:model-value="updateValue"
        :placeholder="field.placeholder"
        :disabled="isDisabled"
        style="width: 200px"
      >
        <template #append>
          <el-button @click="showEmojiPicker = true" :disabled="isDisabled">
            {{ value || '🔍' }}
          </el-button>
        </template>
      </el-input>
      
      <el-dialog v-model="showEmojiPicker" title="选择表情符号" width="400px">
        <div class="emoji-grid">
          <div 
            v-for="emoji in emojiList" 
            :key="emoji"
            class="emoji-item"
            @click="selectEmoji(emoji)"
          >
            {{ emoji }}
          </div>
        </div>
      </el-dialog>
    </div>

    <!-- 颜色选择器 -->
    <el-color-picker
      v-else-if="field.type === 'color'"
      :model-value="value"
      @update:model-value="updateValue"
      :disabled="isDisabled"
    />

    <!-- 日期选择器 -->
    <el-date-picker
      v-else-if="field.type === 'date'"
      :model-value="value"
      @update:model-value="updateValue"
      type="date"
      :placeholder="field.placeholder"
      :disabled="isDisabled"
      style="width: 100%"
    />

    <!-- JSON编辑器 -->
    <div v-else-if="field.type === 'json'" class="json-editor">
      <el-input
        :model-value="jsonDisplay"
        @update:model-value="updateJsonValue"
        type="textarea"
        :rows="6"
        :placeholder="field.placeholder || '输入JSON格式数据'"
        :disabled="isDisabled"
      />
      <div v-if="jsonError" class="json-error">
        <el-text type="danger" size="small">{{ jsonError }}</el-text>
      </div>
    </div>

    <!-- 数组编辑器 -->
    <div v-else-if="field.type === 'array'" class="array-editor">
      <div class="array-header">
        <span class="array-title">{{ field.label }}列表</span>
        <el-button 
          type="primary" 
          size="small" 
          @click="addArrayItem"
          :disabled="isDisabled"
        >
          <el-icon><Plus /></el-icon>
          添加项目
        </el-button>
      </div>
      
      <div class="array-items">
        <div 
          v-for="(item, index) in (value || [])" 
          :key="index"
          class="array-item"
        >
          <div class="array-item-header">
            <span class="item-index">#{{ index + 1 }}</span>
            <el-button 
              type="danger" 
              size="small" 
              circle
              @click="removeArrayItem(index)"
              :disabled="isDisabled"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
          
          <DynamicField
            v-if="field.itemSchema"
            :field="{ ...field.itemSchema, key: `${field.key}[${index}]` }"
            :value="item"
            :form-data="formData"
            @update:value="(val) => updateArrayItem(index, val)"
          />
        </div>
      </div>
    </div>

    <!-- 对象编辑器 -->
    <div v-else-if="field.type === 'object'" class="object-editor">
      <DynamicField
        v-for="(subField, key) in field.properties"
        :key="key"
        :field="subField"
        :value="value?.[key]"
        :form-data="formData"
        @update:value="(val) => updateObjectValue(key, val)"
      />
    </div>

    <!-- 自定义组件 -->
    <component
      v-else-if="field.component"
      :is="field.component"
      :model-value="value"
      @update:model-value="updateValue"
      :field="field"
      :form-data="formData"
      :disabled="isDisabled"
      v-bind="field.componentProps"
    />

    <!-- 未知类型提示 -->
    <el-alert
      v-else
      :title="`未支持的字段类型: ${field.type}`"
      type="warning"
      :closable="false"
    />

    <!-- 字段描述 -->
    <div v-if="field.description" class="field-description">
      {{ field.description }}
    </div>
  </el-form-item>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import type { FieldSchema, FieldOption } from '@/types/schema'
import { Plus, Delete } from '@element-plus/icons-vue'

interface Props {
  field: FieldSchema
  value: any
  formData: Record<string, any>
}

interface Emits {
  (e: 'update:value', value: any): void
  (e: 'validate', fieldKey: string): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const tagInputVisible = ref(false)
const tagInputValue = ref('')
const tagInput = ref()
const showEmojiPicker = ref(false)
const jsonError = ref('')

// 表情符号列表
const emojiList = [
  '⚔️', '🗡️', '🏹', '🛡️', '👑', '💍', '📿', '🥾', '🧤',
  '⚡', '🔥', '❄️', '🌟', '💎', '🔮', '📜', '🧿', '💊',
  '🎯', '🛡️', '⚡', '🌊', '🌿', '🔥', '❄️', '⭐', '💫'
]

// 计算属性
const fieldClass = computed(() => ({
  'dynamic-field': true,
  [`field-type-${props.field.type}`]: true,
  'field-required': props.field.required
}))

const isVisible = computed(() => {
  if (props.field.visible === false) return false
  
  if (typeof props.field.visible === 'string') {
    // 这里可以实现表达式求值
    return true
  }
  
  if (props.field.showWhen) {
    for (const condition of props.field.showWhen) {
      const fieldValue = props.formData[condition.field]
      
      switch (condition.operator) {
        case '==':
          if (fieldValue !== condition.value) return false
          break
        case '!=':
          if (fieldValue === condition.value) return false
          break
        case 'contains':
          if (Array.isArray(fieldValue) && !fieldValue.includes(condition.value)) return false
          break
        case 'in':
          if (!Array.isArray(condition.value) || !condition.value.includes(fieldValue)) return false
          break
      }
    }
  }
  
  return true
})

const isDisabled = computed(() => {
  if (typeof props.field.disabled === 'boolean') return props.field.disabled
  if (typeof props.field.disabled === 'string') {
    // 这里可以实现表达式求值
    return false
  }
  return false
})

const fieldOptions = computed(() => {
  if (props.field.options) return props.field.options
  
  if (props.field.optionsSource) {
    // 这里可以从动态数据源获取选项
    // 例如从服务器获取或从其他字段计算
    return []
  }
  
  return []
})

const jsonDisplay = computed(() => {
  if (props.value === undefined || props.value === null) return ''
  if (typeof props.value === 'string') return props.value
  return JSON.stringify(props.value, null, 2)
})

// 方法
const updateValue = (newValue: any) => {
  emit('update:value', props.field.key, newValue)
}

const updateRangeValue = (type: 'min' | 'max', newValue: number) => {
  const currentValue = props.value || {}
  const updatedValue = { ...currentValue, [type]: newValue }
  updateValue(updatedValue)
}

const updateJsonValue = (newValue: string) => {
  jsonError.value = ''
  
  if (!newValue.trim()) {
    updateValue(null)
    return
  }
  
  try {
    const parsed = JSON.parse(newValue)
    updateValue(parsed)
  } catch (error) {
    jsonError.value = '无效的JSON格式'
    // 仍然更新原始字符串值，让用户继续编辑
    updateValue(newValue)
  }
}

const removeTag = (tag: string) => {
  const currentTags = props.value || []
  const index = currentTags.indexOf(tag)
  if (index > -1) {
    const newTags = [...currentTags]
    newTags.splice(index, 1)
    updateValue(newTags)
  }
}

const showTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    tagInput.value?.focus()
  })
}

const handleTagInputConfirm = () => {
  if (tagInputValue.value && !(props.value || []).includes(tagInputValue.value)) {
    const newTags = [...(props.value || []), tagInputValue.value]
    updateValue(newTags)
  }
  tagInputVisible.value = false
  tagInputValue.value = ''
}

const selectEmoji = (emoji: string) => {
  updateValue(emoji)
  showEmojiPicker.value = false
}

const addArrayItem = () => {
  const currentArray = props.value || []
  const defaultValue = props.field.itemSchema?.defaultValue || {}
  updateValue([...currentArray, defaultValue])
}

const removeArrayItem = (index: number) => {
  const currentArray = props.value || []
  const newArray = [...currentArray]
  newArray.splice(index, 1)
  updateValue(newArray)
}

const updateArrayItem = (index: number, newValue: any) => {
  const currentArray = props.value || []
  const newArray = [...currentArray]
  newArray[index] = newValue
  updateValue(newArray)
}

const updateObjectValue = (key: string, newValue: any) => {
  const currentObject = props.value || {}
  const newObject = { ...currentObject, [key]: newValue }
  updateValue(newObject)
}
</script>

<style scoped>
.dynamic-field {
  margin-bottom: 20px;
}

.field-description {
  margin-top: 4px;
  font-size: 12px;
  color: var(--config-editor-text-secondary);
  line-height: 1.4;
}

.range-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.range-separator {
  color: var(--config-editor-text-secondary);
  font-weight: 500;
}

.tags-input {
  min-height: 32px;
}

.emoji-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.emoji-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 8px;
  padding: 16px;
  max-height: 300px;
  overflow-y: auto;
}

.emoji-item {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 32px;
  height: 32px;
  font-size: 18px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.emoji-item:hover {
  background-color: var(--config-editor-border);
}

.json-editor {
  width: 100%;
}

.json-error {
  margin-top: 4px;
}

.array-editor {
  border: 1px solid var(--config-editor-border);
  border-radius: 6px;
  overflow: hidden;
}

.array-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: var(--config-editor-bg);
  border-bottom: 1px solid var(--config-editor-border);
}

.array-title {
  font-weight: 500;
  color: var(--config-editor-text);
}

.array-items {
  padding: 16px;
}

.array-item {
  margin-bottom: 16px;
  padding: 12px;
  border: 1px solid var(--config-editor-border);
  border-radius: 4px;
  background: var(--config-editor-card-bg);
}

.array-item:last-child {
  margin-bottom: 0;
}

.array-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.item-index {
  font-weight: 500;
  color: var(--config-editor-text-secondary);
}

.object-editor {
  padding: 16px;
  border: 1px solid var(--config-editor-border);
  border-radius: 6px;
  background: var(--config-editor-card-bg);
}

.option-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.option-description {
  font-size: 12px;
  color: var(--config-editor-text-secondary);
  margin-left: 8px;
}

.field-required :deep(.el-form-item__label::before) {
  content: '*';
  color: var(--config-editor-danger);
  margin-right: 4px;
}
</style>
